import React, { Component } from "react";

import {
    Card,
    Button,
    Table,
    Modal,
    Space,
    message
} from 'antd'

import { formateDate } from "../../utils/dateUtils"
import { reqAddOrUpdateUser, reqDeleteUser, reqUsers } from "../../api";
import UserForm from "./user-form";

/**
 * 用户管理
 */
export default class User extends Component {

    constructor(props) {
        super(props);
        this.userForm = React.createRef();
    }

    state = {
        users: [],      // 所有的用户列表
        isShow: false,   // 是否显示确认框
        loading: false,
        roles: []       // 所有角色的列表
    }

    /**
     * 根据role的数组, 生成包含所有角色名的对象(属性名用角色id值)
     */
    initRoleNames = (roles) => {
        const roleNames = roles.reduce((pre, role) => {
            pre[role._id] = role.name
            return pre
        }, {})
        // 保存
        this.roleNames = roleNames
    }

    // 初始化Table列的数组
    initColums = () => {
        this.columns = [
            {
                title: '用户名',
                dataIndex: 'username'
            },
            {
                title: '邮箱',
                dataIndex: 'email'
            },
            {
                title: '电话',
                dataIndex: 'phone'
            },
            {
                title: '注册时间',
                dataIndex: 'create_time',
                render: formateDate,
            },
            {
                title: '所属角色',
                dataIndex: 'role_id',
                render: (role_id) => this.roleNames[role_id]
            },
            {
                title: '操作',
                // width: 800,
                render: (user) => (
                    <Space>
                        <Button type="link" block onClick={() => this.showUpdate(user)}>修改</Button>
                        <Button type="link" block onClick={() => this.deleteUser(user)}>删除</Button>
                    </Space>
                ),
            },
        ];
    }
    // 添加或更新用户
    addOrUpdateUser = () => {
        let userForm = this.userForm.current.refs.form;
        
        userForm.validateFields()
            .then(async values => {

                // console.log(values);
                const user = values

                // 1. 收集输入数据                
                userForm.resetFields()

                // 如果是更新, 需要给user指定_id属性
                if (this.user) {
                    user._id = this.user._id
                }
                // 2. 提交添加的请求
                const result = await reqAddOrUpdateUser(user)
                
                this.setState({isShow: false})

                // 3. 更新列表显示
                if (result.status === 0) {
                    message.success(`${this.user ? '修改' : '添加'}用户成功`)
                    this.getUsers()
                }
            })
            .catch(info => {
                console.log(info);
            });
    }
    // 显示修改页面
    showUpdate = (user) => {
        this.user = user // 保存user
        this.setState({
            isShow: true
        })
    }

    // 删除用户
    deleteUser = (user) => {
        Modal.confirm({
            title: `确认删除${user.username}吗?`,
            onOk: async () => {
                const result = await reqDeleteUser(user._id)
                if (result.status === 0) {
                    message.success('删除用户成功!')
                    this.getUsers()
                }
            }
        })
    }

    getUsers = async () => {
        const result = await reqUsers();
        console.log(result);
        if (result.status === 0) {
            const { users, roles } = result.data;
            this.initRoleNames(roles)
            this.setState({
                users,
                roles
            })
        }
    }
    componentWillMount() {
        this.initColums();
    }

    componentDidMount() {
        this.getUsers();
    }

    render() {
        const user = this.user || {}
        const title = <Button type="primary" onClick={() => this.setState({ isShow: true })}>创建用户</Button>;
        const { users, loading, isShow, roles } = this.state;
        return (
            <Card title={title}>
                <Table
                    dataSource={users}
                    columns={this.columns}
                    bordered
                    rowKey="_id"
                    loading={loading}
                    pagination={{ defaultPageSize: 3 }}
                />

                <Modal
                    title={user._id ? '修改用户' : '添加用户'}
                    visible={isShow}
                    onOk={this.addOrUpdateUser}
                    onCancel={() => {
                        this.userForm.current.refs.form.resetFields()
                        this.setState({ isShow: false })
                    }}
                >
                    {/* <UserForm
                        setForm={form => this.form = form}
                        roles={roles}
                        user={user}
                    /> */}
                    <UserForm
                        ref={this.userForm}
                        setForm={form => this.form = form}
                        roles={roles}
                        user={user}
                    ></UserForm>
                </Modal>
            </Card>
        );
    }
}